package kalambury.srv.packets;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;

/**
 * Created with IntelliJ IDEA.
 * User: ufoq
 * Date: 20.11.12
 * Time: 01:46
 * To change this template use File | Settings | File Templates.
 */
public class ImagePacket extends Packet {
    public int[] imageData;
    public int width;
    public int height;

    public ImagePacket(){}

    public ImagePacket(Image img) {
        try {
            width = img.getWidth(null);
            height = img.getHeight(null);
            imageData = getArrayFromImage(img, width , height);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Image getImageFromData() {
        return getImageFromArray(imageData,width,height);
    }

    private int[] getArrayFromImage(Image img, int width, int height) throws
            InterruptedException {
        int[] pixels = new int[width * height];
        PixelGrabber pg = new PixelGrabber(img, 0, 0, width, height, pixels,
                0, width);
        pg.grabPixels();
        return pixels;
    }

    private Image getImageFromArray(int[] pixels, int width, int height) {
        MemoryImageSource mis = new MemoryImageSource(width, height, pixels,
                0, width);
        Toolkit tk = Toolkit.getDefaultToolkit();
        return tk.createImage(mis);
    }
}
